package com.xyd.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyd.auth.mapper.SysRoleMapper;
import com.xyd.auth.mapper.SysUserRoleMapper;
import com.xyd.auth.service.ISysRoleService;
import com.xyd.model.system.SysRole;
import com.xyd.model.system.SysUserRole;
import com.xyd.model.system.vo.AssignRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl
        extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    /**
     * 根据用户id获取其角色
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> findRoleByUserId(Long userId) {
        // 查询所有的角色
        List<SysRole> list = this.list();
        //拥有的角色id
        // 创建条件对象
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        wrapper.select(SysUserRole::getRoleId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(wrapper);

        // 将以上对象的roleId封装成list
//        ArrayList<Long> sysRoleIds = new ArrayList<>();
//        for(SysUserRole sysUserRole : sysUserRoles){
//            sysRoleIds.add(sysUserRole.getRoleId());
//        }

        List<Long> roleIds =sysUserRoles.stream().map(c -> c.getRoleId()).collect(Collectors.toList());

        //对角色进行分类
        ArrayList<SysRole> assignRoleList = new ArrayList<>();
        for (SysRole sysRole : list) {
            // 已分配的角色
            if(roleIds.contains(sysRole.getId())){
                // 如果当前角色的id存在与查询回来的roleIds集合中
                assignRoleList.add(sysRole);
            }
        }

        HashMap<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignRoleList",assignRoleList); // 将已经分配的角色存入map中
        roleMap.put("allRoleList",list); // 将所有的角色存入到map中

        return roleMap;
    }
    /**
     * 分配角色
     * @param assignRoleVO
     */
    @Override
    public void doAssignRole(AssignRoleVO assignRoleVO) {
        // 删除该用户的原有角色
        sysUserRoleMapper.delete(
                new LambdaQueryWrapper<SysUserRole>().eq(
                        SysUserRole::getUserId,assignRoleVO.getUserId()));

        // 分配角色
        for(Long roleId : assignRoleVO.getRoleIdList()){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assignRoleVO.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
